package com.example.crondemo.task;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.example.crondemo.exception.TaskException;
import com.example.crondemo.model.Stock;
import com.example.crondemo.result.ResultCodeEnum;
import com.example.crondemo.service.StockService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author yanbl
 * @version V1.8
 * @Description: 定时任务 每隔五分钟去接口增量拉取一次库存
 * @Date 2021/7/1 17:20
 */
@EnableScheduling
@Component
public class AsynStockTask {

    @Autowired
    private StockService stockService;

    @Scheduled(cron = "0 0/5 * * * ?") // 五分钟执行一次
    public void task() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 当前时间
        String endTime = sdf.format(new Date());
        // 五分钟前的时间
        String startTime = sdf.format(new DateTime().minusMinutes(5).toDate());
        // 根据时间来获取接口中的数据
        List<Stock> stocks = stockService.findStockInvoke(startTime, endTime);

        // 如果当前对象不为空 就添加到数据库中
        // 如果失败则抛出异常
        if (ObjectUtils.isNotEmpty(stocks)) {
            stocks.forEach(stock -> {
                System.out.println(stock.getCreated());
            });
            stockService.addStocks(stocks);
        } else {
            throw new TaskException(ResultCodeEnum.STOCKSNULL);
        }
    }
}
